package meijuli.com.join51.business.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.bumptech.glide.Glide;
import com.jhx.common.activity.PicturePreviewActivity;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import cn.finalteam.rxgalleryfinal.ui.RxGalleryListener;
import cn.finalteam.rxgalleryfinal.ui.base.IMultiImageCheckedListener;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;
import meijuli.com.join51.business.aliyun.AliyunOSS;
import meijuli.com.join51.business.aliyun.UploadListener;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.Category;
import meijuli.com.join51.business.model.Commodity;
import com.jhx.common.model.Event;
import com.jhx.common.widget.CommonDialog;
import com.jhx.common.widget.LoadingDialog;

import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.LogUtils;
import meijuli.com.join51.business.utils.PermissionUtils;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 添加或编辑商品页面
 *
 * @author jack 2017-04-25 14:26
 */
public class AddCommodityActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    Toolbar mToolbar;
    EditText mNameEdit;
    EditText mPriceEdit;
    EditText mNumberEdit;
    EditText mDescriptionEdit;
    EditText mCostPriceEdit;
    TextView mTitleText;
    TextView mCategoryText;
    RecyclerView mAddRecyclerView;
    TextView mMenuText;
    FrameLayout mCategoryFL;
    private String TAG = getClass().getName();
    private LoadingDialog mLoadingDialog;
    public static final String KEY_TYPE = "OperationType";
    public static final String KEY_INDEX = "index";
    public static final String KEY_DATA = "data";
    public static final String KEY_COMMODITY = "commodity";
    public static final int TYPE_ADD = 1;
    public static final int TYPE_EDIT = 2;
    private ArrayList<MediaBean> mImageList;
    private CustomAdapter<MediaBean> mAdapter;
    /**
     * 商品图片最多可选数量
     */
    private static final int MAX_SIZE = 5;
    /**
     * 上传成功图片数量
     */
    private int successSize = 0;
    /**
     * 上传失败图片数量
     */
    private int errorSize = 0;
    private String mCategoryId = "";
    private List<String> mUrlList;
    private int mCount = MAX_SIZE;
    private int editType = 0;
    private Category mSelCategory;
    private String commodityId = null;
    private Call<HttpResponse<String>> mCall;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_commodity);
        mToolbar = findViewById(R.id.toolbar);
        mNameEdit = findViewById(R.id.edit_name);
        mPriceEdit = findViewById(R.id.edit_price);
        mNumberEdit = findViewById(R.id.edit_num);
        mDescriptionEdit = findViewById(R.id.edit_description);
        mCostPriceEdit = findViewById(R.id.edit_cost_price);
        mTitleText = findViewById(R.id.toolbar_title);
        mCategoryText = findViewById(R.id.text_category_name);
        mAddRecyclerView = findViewById(R.id.rv_addPic);
        mMenuText = findViewById(R.id.text_menu);
        mCategoryFL = findViewById(R.id.fl_category);
        initToolbar();
        initData();
        AliyunOSS.get().init();
        mCategoryFL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddCommodityActivity.this, ClassificationActivity.class);
                intent.putExtra(ClassificationActivity.KEY_FORM, AddCommodityActivity.class.getName());
                startActivity(intent);
            }
        });
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void setView(Commodity commodity) {
        if (commodity == null) {
            return;
        }
        mCategoryText.setText(commodity.getOneCategoryName());
        mNameEdit.setText(commodity.getGoodsName());
        mPriceEdit.setText(commodity.getPrice() + "");
        mCostPriceEdit.setText(commodity.getFinalPrice());
        mNumberEdit.setText(commodity.getSales() + "");
        mDescriptionEdit.setText(commodity.getGoodsDesc());
        mCategoryId = commodity.getOneCategoryId();
        String urls = commodity.getPicture();
        String[] urlArray = urls.split(",");
        mImageList.clear();
        if (editType == TYPE_EDIT) {
            commodityId = commodity.getDmId();
        }
        for (String url : urlArray) {
            if (url.toUpperCase(Locale.ROOT).startsWith("HTTP://")) {
                MediaBean data = new MediaBean();
                data.setOriginalPath(url);
                mImageList.add(data);
            }
        }
        if (mImageList.size() < MAX_SIZE) {
            MediaBean mediaBean = new MediaBean();
            mImageList.add(mediaBean);
        }
        mAdapter.updateView(mImageList);
    }

    private void initData() {
        if (UserManager.get().checkUserNull(this)) {
            return;
        }
        mImageList = new ArrayList<>();
        mUrlList = new ArrayList<>();
        mImageList.add(new MediaBean());
        mAdapter = new CustomAdapter<MediaBean>(mImageList, this, R.layout.item_add_pic, null) {
            @Override
            public void onBindData(CustomHolder holder, final int position, final MediaBean mediaBean) {
                final ImageView addImage = holder.findView(R.id.img_add);
                ImageView delImage = holder.findView(R.id.img_delete);
                if (TextUtils.isEmpty(mediaBean.getOriginalPath())) {
                    addImage.setImageResource(R.mipmap.add_pic);
                    delImage.setVisibility(View.GONE);
                } else {
                    String path = mediaBean.getOriginalPath();
                    if (path.toUpperCase(Locale.US).startsWith("HTTP://")) {
                        Glide.
                                with(AddCommodityActivity.this).
                                load(mediaBean.getOriginalPath()).
                                centerCrop().
                                into(addImage);
                    } else {
                        try {
                            Glide.with(AddCommodityActivity.this)
                                    .load(new File(mediaBean.getOriginalPath()))
                                    .error(R.mipmap.img_default).into(addImage);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    delImage.setVisibility(View.VISIBLE);
                }
                addImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (TextUtils.isEmpty(mediaBean.getOriginalPath())) {
                            mCount = MAX_SIZE - (mImageList.size() - 1);
                            takePictures(mCount);
                        } else {
                            Intent intent = new Intent(AddCommodityActivity.this, PicturePreviewActivity.class);
                            intent.putParcelableArrayListExtra(PicturePreviewActivity.KEY_LIST, mImageList);
                            intent.putExtra(PicturePreviewActivity.KEY_INDEX, position);
                            startActivity(intent);
                        }
                    }
                });
                delImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MediaBean bean = mImageList.get(mImageList.size() - 1);
                        if (!TextUtils.isEmpty(bean.getOriginalPath())) {
                            mImageList.add(new MediaBean());
                        }
                        mImageList.remove(position);
                        mAdapter.updateView(mImageList);
                    }
                });
            }
        };
        mAddRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mAddRecyclerView.setAdapter(mAdapter);
        if (getIntent() != null) {
            Commodity commodity = (Commodity) getIntent().getSerializableExtra(KEY_COMMODITY);
            if (commodity != null) {
                setView(commodity);
            }
        }
    }

    private void initToolbar() {
        Intent intent = getIntent();
        if (intent.getIntExtra(KEY_TYPE, TYPE_ADD) == TYPE_ADD) {
            mTitleText.setText("添加商品");
        } else {
            mTitleText.setText("编辑商品");
            editType = TYPE_EDIT;
        }
        mMenuText.setText("完成");
        mMenuText.setVisibility(View.VISIBLE);
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mMenuText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!checkEmpty()) {
                    ToastUtil.getInstance().showToast(AddCommodityActivity.this, "~请填写完整数据");
                    return;
                }
                if (mImageList.size() > 0) {
                    mUrlList.clear();
                    for (int i = 0; i < mImageList.size(); i++) {
                        final String path = mImageList.get(i).getOriginalPath();
                        if (!TextUtils.isEmpty(path)) {
                            if (path.toUpperCase(Locale.US).startsWith("HTTP://")) {
                                mUrlList.add(path);
                            } else {
                                startCompression(path);
                            }
                        } else {
                            mImageList.remove(i);
                            i--;
                        }
                    }
                    //全部都是网络图片，直接请求
                    if (mUrlList.size() == mImageList.size()) {
                        startRequest();
                    }
                }
            }
        });
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onBackPressed() {
        showYesNoDialog("退出", "取消", "当前正在编辑状态，退出后编辑的内容将不会保存，确定要退出吗？",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        dialogInterface.dismiss();
                        switch (which) {
                            case DialogInterface.BUTTON_POSITIVE:
                                finish();
                                break;
                                default:
                        }
                    }
                });
    }

    /**
     * 调用图片选择器
     */
    public void takePictures(final int maxSize) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            showPictureSelector(maxSize);
            return;
        }
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            showPictureSelector(maxSize);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CommonDialog dialog = new CommonDialog(this);
                dialog.setMessage("为了保证聚惠侠商家版可以正常使用,请在设置-应用-聚惠侠商家版-权限，开启拍照权限");
                dialog.setConfirmBtn("设置");
                dialog.show();
                dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onConfirmClick(View view) {
                        PermissionUtils.getInstance().toSetting(AddCommodityActivity.this);
                    }

                    @Override
                    public void onCancelClick(View view) {
                        ToastUtil.getInstance().showToast("拍照权限被拒绝");
                    }
                });
            }else {
                EasyPermissions.requestPermissions(this, "应用需要拍照权限，请授权",
                        1001,
                        Manifest.permission.CAMERA);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 显示图片选择器
     *
     * @param maxSize
     */
    public void showPictureSelector(int maxSize) {
        SoftInputUtil.get().hideSoftKeyboard(AddCommodityActivity.this);
        //多选图片
        RxGalleryFinal.
                with(AddCommodityActivity.this).
                image().
                multiple().
                maxSize(maxSize).
                imageLoader(ImageLoaderType.GLIDE).
                subscribe(new RxBusResultSubscriber<ImageMultipleResultEvent>() {
                    @Override
                    protected void onEvent(ImageMultipleResultEvent imageResult) throws Exception {
                        final List<MediaBean> imgList = imageResult.getResult();
                        if (mImageList.size() <= MAX_SIZE) {
                            mImageList.remove(mImageList.size() - 1);
                            for (int i = 0; i < imgList.size(); i++) {
                                final MediaBean bean = imgList.get(i);
                                if (!TextUtils.isEmpty(bean.getOriginalPath())) {
                                    mImageList.add(bean);
                                }
                            }
                            if (mImageList.size() < MAX_SIZE) {
                                mImageList.add(new MediaBean());
                            }
                        }
                        mAdapter.updateView(mImageList);
                        Toast.makeText(getBaseContext(), "已选择" + imageResult.getResult().size() + "张图片", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        CrashReport.postCatchedException(e);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        Toast.makeText(getBaseContext(), "OVER", Toast.LENGTH_SHORT).show();
                    }
                }).openGallery();
        multiListener();
    }

    /**
     * 多选事件都会在这里执行
     */
    public void multiListener() {
        //得到多选的事件
        RxGalleryListener.getInstance().setMultiImageCheckedListener(new IMultiImageCheckedListener() {
            @Override
            public void selectedImg(Object t, boolean isChecked) {
                //这个主要点击或者按到就会触发，所以不建议在这里进行Toast
            }

            @Override
            public void selectedImgMax(Object t, boolean isChecked, int maxSize) {
                Toast.makeText(getBaseContext(), "你最多只能选择" + maxSize + "张图片", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 上传图片
     *
     * @param picPath
     */
    private void uploadHeadImage(String picPath) {
        try {
            AliyunOSS.get().upload(picPath, new UploadListener() {
                @Override
                public void onSuccess(String cloudKey, String sourceFilePath) {
                    successSize++;
                    LogUtils.e(TAG, successSize + "");
                    mUrlList.add(cloudKey);
                    if (mUrlList.size() + errorSize == mImageList.size()) {
                        mLoadingDialog.dismiss();
                        ToastUtil.getInstance().showToast(AddCommodityActivity.this,
                                "图片上传完成，成功" + successSize + "张" + "失败" + errorSize + "张",
                                Toast.LENGTH_SHORT);
                        startRequest();
                    }
                }

                @Override
                public void onProgress(String cloudKey, long progress, long total) {

                }

                @Override
                public void onFailure(String cloudKey, ClientException exception) {
                    errorSize++;
                    LogUtils.e(TAG, errorSize + "");
                    CrashReport.postCatchedException(exception);
                    if (mUrlList.size() + errorSize == mImageList.size()) {
                        mLoadingDialog.dismiss();
                        ToastUtil.getInstance().showToast(AddCommodityActivity.this,
                                "图片上传完成，成功" + successSize + "张" + "失败" + errorSize + "张",
                                Toast.LENGTH_SHORT);
                        if (mUrlList.size() > 0) {
                            startRequest();
                        }
                    }
                }
            });
        } catch (FileNotFoundException e) {
            mLoadingDialog.dismiss();
            CrashReport.postCatchedException(e);
            ToastUtil.getInstance().showToast(AddCommodityActivity.this, "图片上传失败");
            if (mUrlList.size() > 0) {
                startRequest();
            }
        }
    }

    /**
     * 启动压缩
     *
     * @param path
     */
    public void startCompression(String path) {
        try {
            File imgFile = new File(path);
            if (!imgFile.exists() || imgFile.length() == 0) {
                CrashReport.postCatchedException(new RuntimeException("所选文件为空"));
                ToastUtil.getInstance().showToast(this, "获取图片失败, 请重试!");
                return;
            }
            Luban.with(this)
                    .load(imgFile)
                    .setCompressListener(new OnCompressListener() {

                        @Override
                        public void onStart() {
                            //  压缩开始前调用，可以在方法内启动 loading UI
                            mLoadingDialog = new LoadingDialog(AddCommodityActivity.this);
                            mLoadingDialog.setTitle("正在上传图片...");
                            mLoadingDialog.show();
                        }

                        @Override
                        public void onSuccess(File file) {
                            //  压缩成功后，上传到阿里云
                            uploadHeadImage(file.getAbsolutePath());
                        }

                        @Override
                        public void onError(Throwable e) {
                            //  当压缩过去出现问题时调用
                            mLoadingDialog.dismiss();
                            ToastUtil.getInstance().showToast("图片压缩失败，请重试");
                            CrashReport.postCatchedException(e);
                        }
                    }).launch();
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
        }
    }

    public boolean checkEmpty() {
        if (mImageList.size() == 1) {
            MediaBean bean = mImageList.get(0);
            if (bean.getOriginalPath() == null) {
                return false;
            }
        } else if (mImageList.size() < MAX_SIZE) {
            MediaBean mediaBean = mImageList.get(mImageList.size() - 1);
            if (mediaBean.getOriginalPath() == null) {
                mImageList.add(new MediaBean());
            }
        }
        return !(TextUtils.isEmpty(mCategoryText.getText().toString()) ||
                TextUtils.isEmpty(mNameEdit.getText().toString()) ||
                TextUtils.isEmpty(mPriceEdit.getText().toString()) ||
                TextUtils.isEmpty(mCostPriceEdit.getText().toString()) ||
                TextUtils.isEmpty(mNumberEdit.getText().toString()) ||
                TextUtils.isEmpty(mDescriptionEdit.getText().toString()));
    }

    /**
     * 向服务器发起请求
     */
    public void startRequest() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < mUrlList.size(); i++) {
            buffer.append(mUrlList.get(i));
            if (i < mUrlList.size() - 1) {
                buffer.append(",");
            }
        }
        String finalPrice = mCostPriceEdit.getText().toString().trim();
        String price = mPriceEdit.getText().toString().trim();
        String sales = mNumberEdit.getText().toString().trim();
        showLoadingDialog();
        mCall = ApiManager.get().getApiService(ApiService.class).addCommodity(commodityId,
                mCategoryId,
                CommodityManagementActivity.STATUS + "",
                finalPrice,
                price,
                buffer.toString(),
                "",
                sales,
                mDescriptionEdit.getText().toString().trim(),
                mNameEdit.getText().toString().trim());
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback() {
            @Override
            public void onSuccess(String url, Object data) {
                dismissDialog();
                Intent intent = new Intent(AddCommodityActivity.this, AddSuccessActivity.class);
                startActivity(intent);
                EventBus.getDefault().post("refresh");
                Event event = new Event();
                event.setData(mSelCategory);
                EventBus.getDefault().post(event);
                finish();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    @Subscribe
    public void onEvent(Event event) {
        if (event != null && event.getData() != null) {
            mSelCategory = (Category) event.getData();
            mCategoryText.setText(mSelCategory.getCategoryName());
            mCategoryId = mSelCategory.getDmId();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        AliyunOSS.get().recycler();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        showPictureSelector(mCount);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.CAMERA);
        checkPermission(permissionList, "该功能需要使用您的相机，请前往设置-权限管理，开启拍照权限");
    }
}
